import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.management.MBeanServer;
import javax.management.MalformedObjectNameException;
import javax.management.ObjectName;
import javax.management.Query;
import javax.servlet.http.HttpServletRequest;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.management.ManagementFactory;
import java.net.HttpURLConnection;
import java.net.InetAddress;
import java.net.URL;
import java.net.UnknownHostException;
import java.util.Set;

public class SimTest {

    //    public static Logger logger = LoggerFactory.getLogger(SimTest.class);
    public static void main(String[] args) {
//        testThird();
//        testIpAndPort();
//        System.out.println("localUrl:  " + getUrl());

//        String result = sendPost("http://10.169.122.110/gkApi/searchMember", addJSONObject());
//        System.out.println("sendPost方法响应体：  " + result);



        JSONObject responseObject = sendPost("http://10.169.122.110/gkApi/searchMember", addJSONObject());
        System.out.println("searchMember-sendPost方法响应体：  " + responseObject);

        JSONObject responseObject2 = sendPost("http://10.169.122.110/gkApi/searchUserGroup", addJSONObjectUserGroup());
        System.out.println("searchUserGroup-sendPost方法响应体：  " + responseObject2);

//        String str = "aaa";
//        if(str.startsWith("{") && str.endsWith("}"))
//            System.out.println(str + " is a json");
//        else
//            System.out.println(str + "is not a json");
//        String str2 = addJSONObject().toString();
//        if(str2.startsWith("{") && str2.endsWith("}"))
//            System.out.println("str2 is a json");
//        else
//            System.out.println(str2 + "is not a json");

//        System.out.println(testConvert());
    }


    public static JSONObject testConvert(){
        StringBuilder msg = new StringBuilder();
        JSONObject result = new JSONObject();
        msg.append("错误的请求参数：名单组id为空");

        String str = new String();
        str = "I like program";

        result.put("code", -1);
        result.put("msg", msg.toString());
        result.put("str", str);
        return result;
    }


    /**
     * 向指定URL发送POST方法的请求
     *
     * @param url  发送请求的URL
     * @param body 请求参数，为json格式
     * @return 所代表远程资源的响应结果
     */
    public static JSONObject sendPost(String url, JSONObject body)  {
        System.out.println("进入sendPost方法");
        InputStream inputStream = null;
        HttpURLConnection httpURLConnection = null;
        StringBuilder result = new StringBuilder();
        try {
            System.out.println("进入try块");
            URL realUrl = new URL(url);
            System.out.println("realUrl ：" + realUrl);
            //打开和URL之间的连接
            httpURLConnection = (HttpURLConnection) realUrl.openConnection();
            System.out.println("httpURLConnection  " + httpURLConnection);
            // 请求方式
            httpURLConnection.setRequestMethod("POST");
            //设置超时时间
            httpURLConnection.setConnectTimeout(300000);
            httpURLConnection.setReadTimeout(300000);
            //post请求。发送POST请求必须设置如下两行
            //设置是否向 HttpUrlConnection 输出，对于post请求，参数要放在 http 正文内，因此需要设为true，默认为false。
            httpURLConnection.setDoOutput(true);
            //设置是否从 HttpUrlConnection读入，默认为true
            httpURLConnection.setDoInput(true);


            // 设置是否使用缓存
            httpURLConnection.setUseCaches(false);
            // 设置此 HttpURLConnection 实例是否应该自动执行 HTTP 重定向
            httpURLConnection.setInstanceFollowRedirects(true);
            // 设置使用标准编码格式编码参数的名-值对
            httpURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            httpURLConnection.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
//            httpURLConnection.setRequestProperty("Content-Type", "application/json");
//            httpURLConnection.setRequestProperty("Content-Type", "UTF-8");

            // 添加 HTTP HEAD 中的一些参数。


            System.out.println("准备connect实际连接啦");
            //建立实际的连接
            httpURLConnection.connect();
            System.out.println("connect连接成功");

            //发送数据,获取HttpURLCOnnection对象对应的输出流
            OutputStream outputStream = httpURLConnection.getOutputStream();
            System.out.println("outputStream:  " + outputStream);
            //经测试 outputStream为请求的body  "{"username":"admin", "imsi":"460007210437022",...,"pageSize":10 }"
            outputStream.write(JSON.toJSONString(body).getBytes());
            System.out.println("outputStream处理完毕 ");

            outputStream.flush();
            outputStream.close();
            //请求数据。使用inputStream来获取URL的响应
            System.out.println("开始处理inputStream");


            //获取返回码
            int code = httpURLConnection.getResponseCode();
            if(code >= 400){  //415
                inputStream = httpURLConnection.getErrorStream();
            } else {
                inputStream = httpURLConnection.getInputStream();
            }
            //在此处出现问题，经过了catch、finally块
//            inputStream = httpURLConnection.getInputStream();
            System.out.println("inputStream:  " + inputStream);

            byte[] bytes = new byte[1024 * 1024];
            int len;
            while ((len = inputStream.read(bytes)) != -1) {
                result.append(new String(bytes, 0, len));
                System.out.println(new String(bytes, 0, len));
            }
            if(inputStream != null){
                inputStream.close();
            }
            System.out.println("result:  " + result);
            System.out.println("result.toString():  " + result.toString());

//            return JSON.parseObject(result.toString());
        } catch (Exception e){
//            logger.info("服务端发来的POST请求 处理失败");
            System.out.println("服务端发来的POST请求 处理失败");
        }
        finally {
            if(httpURLConnection != null)
                httpURLConnection.disconnect();
        }
//        System.out.println(result);
//        return String.valueOf(result);
//        return result;
        return JSON.parseObject(result.toString());
    }


    public static JSONObject addJSONObject(){
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("username","admin");
        jsonObject.put("password","argus@1234");
        jsonObject.put("id","45");
        jsonObject.put("groupId", 27);
        jsonObject.put("name", "swtest1");
        jsonObject.put("imsi", "460007210437022");
        jsonObject.put("mobile", "13312345678");
        jsonObject.put("position", "xs");
        jsonObject.put("pageIndex", 1);
        jsonObject.put("pageSize", 10);
//        jsonObject.put("id","28");
//        jsonObject.put("parentGroupId", 2);
//        jsonObject.put("groupName", "test");
//        jsonObject.put("pageIndex", 1);
//        jsonObject.put("pageSize", 10);
        return jsonObject;
    }

    public static JSONObject addJSONObjectUserGroup(){
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("username","admin");
        jsonObject.put("password","argus@1234");
        jsonObject.put("id","28");
        jsonObject.put("parentGroupId", 2);
        jsonObject.put("groupName", "test");
        jsonObject.put("pageIndex", 1);
        jsonObject.put("pageSize", 10);
        return jsonObject;
    }

    public static String getUrl(){
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();
        String localAddr = request.getLocalAddr();
        int serverPort = request.getServerPort();
        System.out.println("Ip: " + localAddr + ",  Port: " + serverPort);
        return "http://"+localAddr +":"+ serverPort;
    }

    //获取当前机器的IP、端口号
    public static void testIpAndPort(){
        InetAddress addr = null;
        try {
            addr = InetAddress.getLocalHost();
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
        byte[] ipAddr = addr.getAddress();
        //   addr: ra123/192.168.11.1,  ipAddr: [B@7f31245a
        System.out.println("addr: " + addr + ",  ipAddr: " + ipAddr);
        String ipAddrStr = "";
        for (int i = 0; i < ipAddr.length; i++) {
            if (i > 0) {
                ipAddrStr += ".";
            }
            ipAddrStr += ipAddr[i] & 0xFF;
        }
        System.out.println(ipAddrStr);

        String port = null;
        try {
            port = getLocalPort();
        } catch (MalformedObjectNameException e) {
            e.printStackTrace();
        }
        System.out.println("Port:  " + port);
    }

    /**
     * @return
     * @throws MalformedObjectNameException
     * 获取当前机器的端口号
     */
    public static String getLocalPort() throws MalformedObjectNameException {
        MBeanServer beanServer = ManagementFactory.getPlatformMBeanServer();
        Set<ObjectName> objectNames = beanServer.queryNames(new ObjectName("*:type=Connector,*"),
                Query.match(Query.attr("protocol"), Query.value("HTTP/1.1")));
        ObjectName portAll = objectNames.iterator().next();
        String port = portAll.getKeyProperty("port");
        return port;
    }

    public static void testThird(){
        /**
         String id = "MSG_API_REQ";
//         String id1 = id;
         //        id1 = id1.replace("_REQ", "_RESP");
         //        System.out.println("id1 = " + id1);
         Pattern p = Pattern.compile("_REQ$"); //匹配"_REQ"
         Matcher m = p.matcher(id);
         String idNew = null;
         while(m.find()){
         String str1 = m.group();
         System.out.println(str1);
         id = id.replace(str1,"_RESP");
         idNew = id.replace(str1, "_RESP");
         System.out.println(id);
         System.out.println("idNew = " + idNew);
         }
         System.out.println(id);
         **/

        JSONObject body = new JSONObject();
        body.put("id", 2);
        body.put("groupId", 1);
        body.put("name", "人员姓名");
        body.put("imsi", "460011234512345");
        String url = new String("/api/searcgh");
        StringBuffer newUrl = new StringBuffer(url);
        if(!body.isEmpty()){
            newUrl.append("?");
            for (String key : body.keySet()) {
                newUrl.append(key).append("=").append(body.get(key)).append("&");
            }

            url = newUrl.toString();
            url = url.substring(0, url.length()-1);
        }
        System.out.println(newUrl.toString());
        System.out.println(url);
    }

}
